﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;

namespace ActionTrackerDAO.Base
{
    public class DAOBase<TEntity, TId> where TEntity : class
    {
        
        private static ISession _session;

        protected ISession Session
        {
            get
            {
                if (_session == null)
                    _session = NHConfiguration.sessionFactory.OpenSession();
                return _session;
            }
        }

        public TEntity GetById(TId id)
        {
            Session.Clear();
            TEntity entity = Session.Get<TEntity>(id);
            Session.Flush();
            return entity;
        }

        public List<TEntity> GetAll()
        {
            Session.Clear();
            return (List<TEntity>)Session.QueryOver<TEntity>().List();
        }

        public virtual TEntity SaveOrUpdate(TEntity entity)
        {
            Session.Clear();
            Session.SaveOrUpdate(entity);
            Session.Flush();
            return entity;
        }

        public void Delete(TEntity entity)
        {
            Session.Clear();
            Session.Delete(entity);
            Session.Flush();
        }

    }
}